﻿using System;
using System.Web.UI.WebControls;
using br.com.SistemaChamados.Constants;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Enum;
using br.com.SistemaChamados.Model;
using System.Web.Security;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Util;

public partial class Pages_SectorUpdate : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ViewStateUserKey = Session.SessionID;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        br.com.SistemaChamados.Model.Common.User loggedUser = new br.com.SistemaChamados.Model.Common.User();
        UserController userController = new UserController();
        if (Session[UserConstants.SESSION_USER_LOGGED_IN] != null)
        {
            loggedUser.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
            loggedUser = userController.GetUser(loggedUser);
            this.MasterPageFile = MasterPageDefiner.defineMasterPageByAccessRole(loggedUser.Profile);
            ((Label)Master.FindControl("lblUser")).Text = loggedUser.Name;
            this.Title = "SysCall - Sistema de chamados [logado como " + loggedUser.Name + "]";
        }
        else
        {
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!User.IsInRole("ADMIN"))
        {
            if (!IsPostBack)
            {
                FillDdlState();
                FillData();
            }
        }
        else
        {
            FormsAuthentication.SignOut();
            Response.Clear();
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {

    }

    private void FillDdlState()
    {
        UnitController unitController = new UnitController();
        ddlUnit.DataSource = unitController.GetUnits();
        ddlUnit.DataTextField = "Name";
        ddlUnit.DataValueField = "Id";
        ddlUnit.DataBind();
        ddlUnit.Items.Insert(0, "Selecione");
    }

    private void MatchDdlUnitValue(Sector sector)
    {
        ListItem listUnit = ddlUnit.Items.FindByValue(Convert.ToString(sector.Unit.Id));

        for (int i = 0; i < ddlUnit.Items.Count; i++)
        {
            ddlUnit.Items[i].Selected = false;
        }
        if (listUnit != null)
        {
            listUnit.Selected = true;
        }
        else
        {
            ddlUnit.Items[0].Selected = true;
        }
    }

    private void FillData()
    {
        string id = Session[SectorConstants.SESSION_SECTOR_ID].ToString();
        Sector sector = new Sector();
        SectorController sectorController = new SectorController();
        sector.Id = Convert.ToInt32(id);
        sector = sectorController.GetSector(sector);
        try
        {
            txbDescription.Text = Convert.ToString(sector.Description);
            MatchDdlUnitValue(sector);
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro no carregamento dos valores: <br>" + ex.Message +
                               ".');</script>");
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        Sector sector = new Sector();
        SectorController sectorController = new SectorController();
        br.com.SistemaChamados.Model.Unit unit = null;
        try
        {
            unit = new br.com.SistemaChamados.Model.Unit();
            unit.Id = Convert.ToInt32(ddlUnit.SelectedValue);
            sector.Id = Convert.ToInt32(Session[SectorConstants.SESSION_SECTOR_ID]);
            sector.Description = Convert.ToString(txbDescription.Text);
            sector.Unit = unit;
            EnumCRUDState resultOperation  = sectorController.UpdateSector(sector);
            if (resultOperation == EnumCRUDState.SQL_SUCCESS)
            {
                Response.Write(@"<script language='javascript'>alert('Setor alterado com sucesso!');</script>");
                Response.Redirect("SectorMain.aspx");
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante a alteração, por favor tente novamente!');</script>");
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro ao alterar o setor: <br>" + ex.Message + ".');</script>");
            sector = null;
            sectorController = null;
        }
        finally
        {
            Session.Remove(SectorConstants.SESSION_SECTOR_ID);
        }
    }
}